import React, { useState, useEffect } from 'react';
import { Table, Input, DatePicker, Select, Button, Space, Tag, Tooltip } from 'antd';
import { SearchOutlined, ReloadOutlined, RedoOutlined, DownloadOutlined } from '@ant-design/icons';
import { Dayjs } from 'dayjs';
import { fetchScanLogList } from '../../../../../services/saAnalyser';
import type { SaScanLog, SaScanLogQueryParams } from '../../types';
import { formatDateTime, formatDuration, formatNumber, showError, exportToExcel } from '../../utils';
import './index.less';

const { RangePicker } = DatePicker;
const { Option } = Select;

interface ScanLogTableProps {
    filterUnitId?: string;
    onUnitIdClick?: (unitId: string) => void;
}

const ScanLogTable: React.FC<ScanLogTableProps> = ({ filterUnitId, onUnitIdClick }) => {
    const [loading, setLoading] = useState(false);
    const [dataSource, setDataSource] = useState<SaScanLog[]>([]);
    const [total, setTotal] = useState(0);

    // 筛选条件
    const [unitId, setUnitId] = useState<string>(filterUnitId || '');
    const [dateRange, setDateRange] = useState<[Dayjs | null, Dayjs | null]>([null, null]);
    const [success, setSuccess] = useState<boolean | undefined>(undefined);

    // 分页参数
    const [pageNum, setPageNum] = useState(1);
    const [pageSize, setPageSize] = useState(10);

    // 加载数据
    const loadData = async () => {
        setLoading(true);
        try {
            const params: SaScanLogQueryParams = {
                pageNum,
                pageSize,
                unitId: unitId || undefined,
                startTime: dateRange[0] ? dateRange[0].format('YYYY-MM-DD HH:mm:ss') : undefined,
                endTime: dateRange[1] ? dateRange[1].format('YYYY-MM-DD HH:mm:ss') : undefined,
                success
            };

            const result = await fetchScanLogList(params);
            setDataSource(result.list || []);
            setTotal(result.total || 0);
        } catch (error: any) {
            showError('查询扫描日志失败', error);
            setDataSource([]);
            setTotal(0);
        } finally {
            setLoading(false);
        }
    };

    // 当filterUnitId变化时更新unitId并触发查询
    useEffect(() => {
        if (filterUnitId) {
            setUnitId(filterUnitId);
            setPageNum(1);
        }
    }, [filterUnitId]);

    // 初始加载和参数变化时重新加载
    useEffect(() => {
        loadData();
    }, [pageNum, pageSize]);

    // 查询按钮
    const handleSearch = () => {
        setPageNum(1);
        loadData();
    };

    // 重置按钮
    const handleReset = () => {
        setUnitId('');
        setDateRange([null, null]);
        setSuccess(undefined);
        setPageNum(1);
        // 重置后立即查询
        setTimeout(() => {
            loadData();
        }, 0);
    };

    // 刷新按钮
    const handleRefresh = () => {
        loadData();
    };

    // 导出按钮
    const [exporting, setExporting] = useState(false);
    const handleExport = async () => {
        setExporting(true);
        try {
            // 获取所有数据（不分页）
            const params: SaScanLogQueryParams = {
                pageNum: 1,
                pageSize: 999999, // 获取所有数据
                unitId: unitId || undefined,
                startTime: dateRange[0] ? dateRange[0].format('YYYY-MM-DD HH:mm:ss') : undefined,
                endTime: dateRange[1] ? dateRange[1].format('YYYY-MM-DD HH:mm:ss') : undefined,
                success
            };

            const result = await fetchScanLogList(params);
            const exportData = result.list || [];

            if (exportData.length === 0) {
                showError('没有数据可导出');
                return;
            }

            // 定义导出列
            const exportColumns = [
                { header: '单元ID', key: 'unitId' },
                { header: 'IP地址', key: 'ip' },
                { header: '进程KEY', key: 'processKey' },
                {
                    header: '扫描时间',
                    key: 'scanTime',
                    formatter: (value: string) => formatDateTime(value)
                },
                {
                    header: '方法数',
                    key: 'methodCount',
                    formatter: (value: number) => value !== null && value !== undefined ? String(value) : '-'
                },
                {
                    header: '扫描耗时(秒)',
                    key: 'scanDurationMs',
                    formatter: (value: number) => value ? (value / 1000).toFixed(2) : '-'
                },
                {
                    header: '扫描结果',
                    key: 'success',
                    formatter: (value: boolean) => value ? '成功' : '失败'
                },
                { header: '结果摘要', key: 'result' }
            ];

            exportToExcel(exportData, exportColumns, '扫描日志');
        } catch (error: any) {
            showError('导出失败', error);
        } finally {
            setExporting(false);
        }
    };

    // 表格列定义
    const columns = [
        {
            title: '单元ID',
            dataIndex: 'unitId',
            key: 'unitId',
            width: 180,
            fixed: 'left' as const,
            ellipsis: {
                showTitle: false
            },
            render: (text: string) => (
                <Tooltip title={`点击查看单元 ${text} 的分析任务`}>
                    <Button
                        type="link"
                        onClick={() => onUnitIdClick && onUnitIdClick(text)}
                        style={{
                            padding: 0,
                            height: 'auto',
                            fontWeight: '500',
                            color: '#1890ff',
                            maxWidth: '100%',
                            overflow: 'hidden',
                            textOverflow: 'ellipsis',
                            whiteSpace: 'nowrap',
                            display: 'block'
                        }}
                    >
                        {text}
                    </Button>
                </Tooltip>
            )
        },
        {
            title: 'IP地址',
            dataIndex: 'ip',
            key: 'ip',
            width: 150,
            ellipsis: {
                showTitle: false
            },
            render: (text: string) => text ? (
                <Tooltip title={`服务器IP: ${text}`}>
                    <span style={{ color: '#595959', fontFamily: 'monospace' }}>{text}</span>
                </Tooltip>
            ) : (
                <span style={{ color: '#d9d9d9' }}>-</span>
            )
        },
        {
            title: '进程KEY',
            dataIndex: 'processKey',
            key: 'processKey',
            width: 200,
            ellipsis: {
                showTitle: false
            },
            render: (text: string) => text ? (
                <Tooltip title={`进程标识: ${text}`}>
                    <span style={{ color: '#595959', fontFamily: 'monospace', fontSize: '12px' }}>{text}</span>
                </Tooltip>
            ) : (
                <span style={{ color: '#d9d9d9' }}>-</span>
            )
        },
        {
            title: '扫描时间',
            dataIndex: 'scanTime',
            key: 'scanTime',
            width: 180,
            ellipsis: {
                showTitle: false
            },
            render: (text: string) => {
                const formatted = formatDateTime(text);
                return (
                    <Tooltip title={formatted}>
                        <span style={{ color: '#595959' }}>{formatted}</span>
                    </Tooltip>
                );
            }
        },
        {
            title: '方法数',
            dataIndex: 'methodCount',
            key: 'methodCount',
            width: 120,
            align: 'right' as const,
            render: (count: number) => {
                const displayValue = count !== null && count !== undefined ? formatNumber(count) : '-';
                return (
                    <Tooltip title={count !== null && count !== undefined ? `共扫描 ${count} 个方法` : '无数据'}>
                        <span style={{ color: '#595959', fontWeight: '500' }}>
                            {displayValue}
                        </span>
                    </Tooltip>
                );
            }
        },
        {
            title: '扫描耗时',
            dataIndex: 'scanDurationMs',
            key: 'scanDurationMs',
            width: 120,
            align: 'right' as const,
            render: (ms: number) => {
                const formatted = formatDuration(ms);
                return (
                    <Tooltip title={ms ? `耗时: ${ms}ms (${formatted})` : '无数据'}>
                        <span style={{ color: '#595959' }}>{formatted}</span>
                    </Tooltip>
                );
            }
        },
        {
            title: '扫描结果',
            dataIndex: 'success',
            key: 'success',
            width: 120,
            fixed: 'right' as const,
            render: (success: boolean) => {
                const label = success ? '成功' : '失败';
                const color = success ? 'success' : 'error';
                return (
                    <Tooltip title={`扫描${label}`}>
                        <Tag color={color}>
                            {label}
                        </Tag>
                    </Tooltip>
                );
            }
        },
        {
            title: '结果摘要',
            dataIndex: 'result',
            key: 'result',
            width: 300,
            ellipsis: {
                showTitle: false
            },
            render: (text: string) => text ? (
                <Tooltip title={text} placement="topLeft">
                    <span style={{ color: '#595959' }}>{text}</span>
                </Tooltip>
            ) : (
                <span style={{ color: '#d9d9d9' }}>-</span>
            )
        }
    ];

    return (
        <div className="scan-log-table">
            {/* 筛选栏 */}
            <div className="filter-bar">
                <Space size="middle" wrap>
                    <Input
                        placeholder="请输入单元ID"
                        value={unitId}
                        onChange={(e) => setUnitId(e.target.value)}
                        onPressEnter={handleSearch}
                        style={{ width: 200 }}
                        allowClear
                    />

                    <RangePicker
                        value={dateRange}
                        onChange={(dates) => setDateRange(dates as [Dayjs | null, Dayjs | null])}
                        showTime
                        format="YYYY-MM-DD HH:mm:ss"
                        placeholder={['开始时间', '结束时间']}
                        style={{ width: 380 }}
                    />

                    <Select
                        placeholder="扫描结果"
                        value={success}
                        onChange={setSuccess}
                        style={{ width: 140 }}
                        allowClear
                    >
                        <Option value={true}>成功</Option>
                        <Option value={false}>失败</Option>
                    </Select>

                    <Button
                        type="primary"
                        icon={<SearchOutlined />}
                        onClick={handleSearch}
                        loading={loading}
                    >
                        查询
                    </Button>

                    <Button
                        icon={<RedoOutlined />}
                        onClick={handleReset}
                    >
                        重置
                    </Button>

                    <Button
                        icon={<ReloadOutlined />}
                        onClick={handleRefresh}
                        loading={loading}
                    >
                        刷新
                    </Button>

                    <Button
                        icon={<DownloadOutlined />}
                        onClick={handleExport}
                        loading={exporting}
                    >
                        导出
                    </Button>
                </Space>
            </div>

            {/* 数据表格 */}
            <Table
                rowKey="id"
                columns={columns}
                dataSource={dataSource}
                loading={{
                    spinning: loading,
                    tip: '加载中...',
                    size: 'large'
                }}
                scroll={{ x: 1400, y: 'calc(100vh - 400px)' }}
                pagination={{
                    current: pageNum,
                    pageSize: pageSize,
                    total: total,
                    showSizeChanger: true,
                    showQuickJumper: true,
                    showTotal: (total, range) => (
                        <span style={{ color: '#595959', fontWeight: '500' }}>
                            显示第 {range[0]}-{range[1]} 条，共 {total} 条记录
                        </span>
                    ),
                    pageSizeOptions: ['10', '20', '50', '100'],
                    onChange: (page, size) => {
                        setPageNum(page);
                        if (size !== pageSize) {
                            setPageSize(size);
                            setPageNum(1); // 改变每页大小时重置到第一页
                        }
                    },
                    position: ['bottomCenter']
                }}
                size="middle"
                style={{
                    background: '#fff',
                    borderRadius: '8px'
                }}
                rowClassName={() => 'hover-row'}
                locale={{
                    emptyText: (
                        <div style={{ padding: '40px 0' }}>
                            <div style={{ fontSize: '48px', color: '#d9d9d9', marginBottom: '16px' }}>📋</div>
                            <div style={{ color: '#8c8c8c', fontSize: '14px' }}>暂无数据</div>
                            <div style={{ color: '#bfbfbf', fontSize: '12px', marginTop: '8px' }}>
                                请调整筛选条件后重试
                            </div>
                        </div>
                    )
                }}
            />
        </div>
    );
};

export default ScanLogTable;
